package top.yangyitao.service.impl;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import top.yangyitao.dao.AttendanceRecordRepository;
import top.yangyitao.entity.AttendanceRecord;
import top.yangyitao.entity.PaySlip;
import top.yangyitao.service.AttendanceRecordService;

@Service
public class AttendanceRecordServiceImpl implements AttendanceRecordService{

	@Autowired
	AttendanceRecordRepository attendanceRecordDao;
	
	@Override
	public Page<AttendanceRecord> getAttendanceRecordPage(Integer pageNumber, Integer pageSize, Long organizationId,
			Long userId, String startDay, String endDay, String search) {
		if(pageNumber == null || pageNumber <= 0) {
			pageNumber = 1;
		}
		if(pageSize == null || pageSize <= 0) {
			pageSize = 10;
		}
		Sort sort = new Sort(Sort.Direction.ASC,"id");
		PageRequest pageRequest = new PageRequest(pageNumber-1,pageSize,sort);
		Specification<AttendanceRecord> spec = new Specification<AttendanceRecord>() {
			@Override
			public Predicate toPredicate(Root<AttendanceRecord> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate pre = criteriaBuilder.conjunction();
				if(organizationId!=null) {
					pre = criteriaBuilder.and(pre,criteriaBuilder.equal(root.get("user").get("organization").get("id"), organizationId.longValue()));
				}
				if(userId!=null) {
					pre = criteriaBuilder.and(pre,criteriaBuilder.equal(root.get("user").get("id"), userId.longValue()));
				}
				if(startDay!=null && startDay.trim().length()!=0) {
					pre = criteriaBuilder.and(pre,criteriaBuilder.greaterThanOrEqualTo(root.get("checkTime"), startDay+" 00:00"));
				}
				if(endDay!=null && endDay.trim().length()!=0) {
					pre = criteriaBuilder.and(pre,criteriaBuilder.lessThanOrEqualTo(root.get("checkTime"), endDay+" 23:59"));
				}
				if(search!=null && search.trim().length()!=0) {
					pre = criteriaBuilder.and(pre,criteriaBuilder.like(root.get("user").get("nickname"), "%"+search+"%"));
				}
				return pre;
			}
			
		};
		return attendanceRecordDao.findAll(spec, pageRequest);
	}


	@Override
	public void addAttendanceRecord(AttendanceRecord attendanceRecord) {
		attendanceRecordDao.saveAndFlush(attendanceRecord);
	}

	@Override
	public void save(AttendanceRecord attendanceRecord) {
		attendanceRecordDao.saveAndFlush(attendanceRecord);
	}

}
